<?php
date_default_timezone_set("US/Central");
$vars = parse_ini_file("../ini/settings.ini");
$connect = mysql_connect($vars["mysql_host"],$vars["mysql_username"],$vars["mysql_password"]) or die(mysql_error());
$db = mysql_select_db($vars["mysql_database"],$connect);


$name=$_POST['name'];
$airdate = $_POST['airdate'];
$id = $_POST['id'];
$gd = $_POST['gd'];
$hasd = $_POST['hasd'];
$getlink = $_POST['getlink'];

$sql = "SELECT episode_num_dd_progid,notvdb from torecord where id=\"$id\"";
$result = mysql_query($sql,$connect) or die (mysql_error());
$row = mysql_fetch_row($result);
$episode_num_dd_progid = $row[0];
$ntvdb = $row[1];
if ($ntvdb == 1) {
	if ($getlink == 0) {
		echo "Skipping On Purpose\n";
	}
	exit;
}

$sql = "select description from listings where episode_num_dd_progid =\"$episode_num_dd_progid\" and description != \"\" limit 1";
$result = mysql_query($sql,$connect) or die (mysql_error());
$row = mysql_fetch_row($result);
$description = $row[0];

if ($gd == 1) {
	echo $description;
	exit;
}
//$name ="Yard.Crashers.S07E12.";


if (trim($name) == "" || trim($airdate) == "") {
	exit;
}


$regexp = "S([0-9][0-9]?[0-9])E([0-9][0-9]?[0-9])";
if(preg_match_all("/$regexp/siU", $name, $matches)) { 
	$season=$matches[1][0];
	$episode=$matches[2][0];
}
$sp = explode("S".$season."E".$episode,$name);
$show = str_replace("."," ",$sp[0]);
$episodename = str_replace("."," ",$sp[1]);
$show = trim($show);
$episodename = trim($episodename);

if ($show == "Amish Out of Order") {
	$show = "Amish: Out of Order";
}

if ($episodename == "") {
	$episodename="TBA";
}

if ($episodename == "TBA") {
	$sql = "UPDATE torecord set tvdb=1,tba=1 where id=$id";
	$result = mysql_query($sql,$connect) or die (mysql_error());
} else {
	$sql = "UPDATE torecord set tvdb=1 where id=$id";
	$result = mysql_query($sql,$connect) or die (mysql_error());
}

$time = strtotime($airdate);
$airdate = date("Y-m-d",$time);


$ckfile="/tmp/thetvdb";
$username=$vars["tvdb_username"];
$password=$vars["tvdb_password"];


if (startsWith($season, "0")){
	$season = substr($season,1,1);
}
if (startsWith($episode, "0")){
	$episode = substr($episode,1,1);
}


login($ckfile,$username,$password);
$id = getShowId($ckfile,$show);
if ($id == -1) {
	if ($getlink == 0) {
		echo "Show Not Found or Found more then one...\n";
	}
	exit;
}

if (!checkIfSeason($ckfile,$season,$id)) {
	//echo "Adding";
	addSeason($ckfile,$season,$id);
}

$seasonid = getSeasonid($ckfile,$season,$id);

$episodeid = checkIfEpisode($ckfile,$season,$id,$seasonid,$episode);
if ($episodeid == "" ) {
	if ($getlink == 0) {
		echo "Episode Not Found... Adding!\n";
	}
	addEpisode($ckfile,$season,$id,$seasonid,$episode,$episodename);
	$episodeid = checkIfEpisode($ckfile,$season,$id,$seasonid,$episode);
}

if ($episodeid == "") {
	if (getlink == 0) {
		echo "Something went Terribly wrong\n";
	}
	exit;
}
if ($hasd == 1) {
	$description="";
	$showvars=getShowVars($ckfile,$season,$id,$seasonid,$episodeid,$episodename,$description);
	$found = 0;
	foreach($showvars as $key => $val) {
		if (strstr($key,"Overview_")) {
			if ($key != "Overview_LangSelect") {
				if (trim($val) != "") {
					//echo $val;
					echo 1;
					exit;
				}
			}
		}
	}
	echo 0;
	exit;
}
if ($getlink == 1) {
	echo "http://thetvdb.com/?tab=episode&seriesid=$id&seasonid=$seasonid&id=$episodeid";
	exit;
}
//see if we know when this show was first aired
$showvars=getShowVars($ckfile,$season,$id,$seasonid,$episodeid,$episodename,$description);

//echo "First Aired: ". $showvars['FirstAired'] ."\n";

if ($airdate != "") {
	if ($showvars['FirstAired'] != $airdate) {
		$showvars["FirstAired"] = $airdate;
		setFirstAired($ckfile,$season,$id,$seasonid,$episodeid,$showvars);
	}
}

foreach ($showvars as $key => $value) {
	$showvars["$key"] = urldecode($value);
}


//find the nonblank episode name
$change = 0;
foreach($showvars as $key => $value) {
	if (strstr($key,"EpisodeName_")) {
		if (!strstr($key,"EpisodeName_LangSelect")) {
			if ($value != "") {
				//if ($value != $name) {
					$change=1;
					$showvars["$key"] = $episodename;
				//}
			}
		}
	}
}

if ($change == 1 || $description != "") {
	setName($ckfile,$season,$id,$seasonid,$episodeid,$showvars);
}


echo "Done";

function setName($ckfile,$season,$showid,$seasonid,$episodeid,$showvars) {
	$fields_string="";
	$url = "http://thetvdb.com/index.php?tab=episode&seriesid=$showid&seasonid=$seasonid&id=$episodeid";
	//echo $url;
	foreach ($showvars as $key => $value) {
		$showvars["$key"] = urlencode($value);
	}
	$fields = $showvars;
	//print_r($showvars);
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	$ch = curl_init();
	//$query = http_build_query($fields, '', '&');
	//set the url, number of POST vars, POST data
	$headers = array();
	array_push($headers,'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
	array_push($headers,'Connection: Keep-Alive');
	array_push($headers,'Content-type: application/x-www-form-urlencoded');
	array_push($headers,'Accept-Encoding: gzip, deflate');
	array_push($headers,'Accept-Language: en-us,en;q=0.5');
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); 
	curl_setopt($ch,CURLOPT_POST,true);
	curl_setopt($ch,CURLOPT_ENCODING , "gzip");
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:12.0) Gecko/20100101 Firefox/12.0');
	curl_setopt($ch,CURLOPT_REFERER,"http://thetvdb.com/index.php"); 
	curl_setopt($ch,CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 
	
	//execute post
	$result = curl_exec($ch);
	curl_close($ch);

}


function setFirstAired($ckfile,$season,$showid,$seasonid,$episodeid,$showvars) {
	$fields_string="";
	$url = "http://thetvdb.com/index.php?tab=episode&seriesid=$showid&seasonid=$seasonid&id=$episodeid";
	foreach ($showvars as $key => $value) {
		$showvars["$key"] = urlencode($value);
	}
	$fields = $showvars;

	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	$ch = curl_init();
	//$query = http_build_query($fields, '', '&');
	//set the url, number of POST vars, POST data
	$headers = array();
	array_push($headers,'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
	array_push($headers,'Connection: Keep-Alive');
	array_push($headers,'Content-type: application/x-www-form-urlencoded');
	array_push($headers,'Accept-Encoding: gzip, deflate');
	array_push($headers,'Accept-Language: en-us,en;q=0.5');
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); 
	curl_setopt($ch,CURLOPT_POST,true);
	curl_setopt($ch,CURLOPT_ENCODING , "gzip");
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:12.0) Gecko/20100101 Firefox/12.0');
	curl_setopt($ch,CURLOPT_REFERER,"http://thetvdb.com/index.php"); 
	curl_setopt($ch,CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 
	
	//execute post
	$result = curl_exec($ch);
	curl_close($ch);

}

function getShowVars($ckfile,$season,$showid,$seasonid,$episodeid,$episodename,$description) {
	$fields_string="";
	$url="http://thetvdb.com/?tab=episode&seriesid=$showid&seasonid=$seasonid&id=$episodeid";
	//echo $url ."\n";
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt($ch,CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 


	$firstAired="";
	$result = curl_exec($ch);
	$lines = explode("\n",$result);
	$showvars = array();
	//echo $result;
	//exit;
	foreach($lines as $line) {
		if (strstr($line,"name=\"EpisodeName_")) {
			$name_num = explode("name=\"EpisodeName_",$line);
			$name_num = explode("\"",$name_num[1]);
			$name_num = $name_num[0];
			$e = explode("value=\"",$line);
                        if (sizeof($e) ==1) {
                                $e[0] = "";
                        } else {
                                $e = explode("\"",$e[1]);
                        }
			if (strstr($line,"style=\"display: inline\"")) {
				$showvars["EpisodeName_$name_num"] = $episodename;
			} else {
				$showvars["EpisodeName_$name_num"] = "";
			}
		}
		if (strstr($line,"name=\"Overview_")) {
			$name_num = explode("name=\"Overview_",$line);
			$name_num = explode("\"",$name_num[1]);
			$name_num = $name_num[0];
			
			/*$e = explode("value=\"",$line);
			if (sizeof($e) ==1) {
				$e[0] = "";
			} else {
				$e = explode("\"",$e[1]);
			}*/
			if ("Overview_$name_num" != "Overview_LangSelect") {
				if (strstr($line,"none\"></textarea>")) {
					//we got a blank here
					$showvars["Overview_$name_num"]="";
				} else {
					//strip all the tags we got a description
					if ($description != "") {
						$showvars["Overview_$name_num"] = $description;
					} else {
						$showvars["Overview_$name_num"] = strip_tags($line);
					}
				}
			}


			/*
			if ("Overview_$name_num" != "Overview_LangSelect") {
				echo $e[0];
				if (strstr($line,"style=\"display: inline\"")) {
					if ($description != "") {
						$showvars["Overview_$name_num"] = $description;
					} else {
						$showvars["Overview_$name_num"] = $e[0];
					}
				} else {
					$showvars["Overview_$name_num"] = $e[0];
				}
			}
			*/
		}
		
		if (strstr($line,"name=\"function")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['function'] = 'Save Episode';
		}

		if (strstr($line,"name=\"IMDB_ID")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['IMDB_ID'] = $e[0];
		}

		if (strstr($line,"name=\"absolute_number")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['absolute_number'] = $e[0];
		}
		if (strstr($line,"name=\"DVD_chapter")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['DVD_chapter'] = $e[0];
		}

		if (strstr($line,"name=\"DVD_episodenumber")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['DVD_episodenumber'] = $e[0];
		}

		if (strstr($line,"name=\"Overview_LangSelect")) {
			$e = explode("value=\"",$line);
                        if (sizeof($e) ==1) {
                                $e[0] = "";
                        } else {
                                $e = explode("\"",$e[1]);
                        }
			if ($e[0] == "") {
				$e[0] = 7;
			}
			$showvars['Overview_LangSelect'] = $e[0];
		}

		if (strstr($line,"name=\"DVD_season")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['DVD_season'] = $e[0];
		}

		if (strstr($line,"name=\"Overview_LangSelect")) {
			$e = explode("value=\"",$line);
                        if (sizeof($e) ==1) {
                                $e[0] = "";
                        } else {
                                $e = explode("\"",$e[1]);
                        }
			if ($e[0] == "") {
				$e[0] = 7;
			}
			$showvars['Overview_LangSelect'] = $e[0];
		}
		if (strstr($line,"name=\"ProductionCode")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['ProductionCode'] = $e[0];
		}

		if (strstr($line,"name=\"Writer")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['Writer'] = $e[0];
		}
		if (strstr($line,"name=\"Director")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['Writer'] = $e[0];
		}

		if (strstr($line,"name=\"GuestStars")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['GuestStars'] = $e[0];
		}
		
		if (strstr($line,"name=\"EpisodeNumber")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['EpisodeNumber'] = $e[0];
		}
		if (strstr($line,"name=\"EpisodeName_LangSelect")) {
			$e = explode("value=\"",$line);
                        if (sizeof($e) ==1) {
                                $e[0] = "";
                        } else {
                                $e = explode("\"",$e[1]);
                        }
			if ($e[0] == "") {
				$e[0] = 7;
			}
			$showvars['EpisodeName_LangSelect'] = $e[0];
		}
		if (strstr($line,"name=\"EpisodeNumber")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['EpisodeNumber'] = $e[0];
		}
		if (strstr($line,"name=\"FirstAired")) {
			$e = explode("value=\"",$line);
			$e = explode("\"",$e[1]);
			$showvars['FirstAired']=$e[0];
		}
	}
	curl_close($ch);
	foreach ($showvars as $key => $value) {
		$showvars["$key"] = urldecode($value);
	}
	//print_r($showvars);

	//exit;
	return $showvars;
}

function addEpisode($ckfile,$season,$showid,$seasonid,$episode,$episodename) {
	$fields_string="";
	$url="http://thetvdb.com/index.php?tab=season&seriesid=$showid&seasonid=$seasonid";
	$fields = array(
        	    'EpisodeNumber'=>urlencode($episode),
	            'EpisodeName'=>urlencode($episodename),
	            'function'=>urlencode("Add Episode")
        	);
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
		rtrim($fields_string,'&');
		$ch = curl_init();
		//$query = http_build_query($fields, '', '&');
		//set the url, number of POST vars, POST data
		$headers = array();
		array_push($headers,'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
		array_push($headers,'Connection: Keep-Alive');
		array_push($headers,'Content-type: application/x-www-form-urlencoded');
		array_push($headers,'Accept-Encoding: gzip, deflate');
		array_push($headers,'Accept-Language: en-us,en;q=0.5');
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); 
		curl_setopt($ch,CURLOPT_POST,true);
		curl_setopt($ch,CURLOPT_ENCODING , "gzip");
		curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
		curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:12.0) Gecko/20100101 Firefox/12.0');
		curl_setopt($ch,CURLOPT_REFERER,"http://thetvdb.com/index.php"); 
		curl_setopt($ch,CURLOPT_COOKIEJAR, $ckfile); 
		curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 
		
		//execute post
		$result = curl_exec($ch);
		curl_close($ch);
}


function checkIfEpisode($ckfile,$season,$showid,$seasonid,$episode) {
	$fields_string="";
	$url="http://thetvdb.com/?tab=season&seriesid=$showid&seasonid=$seasonid";
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 

	$result = curl_exec($ch);
	$lines = explode("\n",$result);
	$ids=array();
	$match_numbers = array();
	$match_links = array();
	foreach($lines as $line) {
		if (strstr($line,"a href=\"/?tab=episode&seriesid=")) {
			$e = explode("</td>",$line);
			$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
			if(preg_match_all("/$regexp/siU", $e[0], $matches)) { 
				// $matches[2] = array of link addresses 
				// $matches[3] = array of link text - including HTML code 
				foreach($matches[3] as $m ) {
					array_push($match_numbers,$m);
				}
				foreach($matches[2] as $m ) {
					array_push($match_links,$m);
				}
			}
		}
	}
	$count = 0;
	$episodeid = "";
	foreach($match_numbers as $match) {
		if ($match == $episode) {
			//$found = true;
			$e = explode("&id=",$match_links[$count]);
			$e = explode("&amp;",$e[1]);
			$episodeid=$e[0];
		}
		$count++;
	}
	curl_close($ch);
	return $episodeid;

        curl_close($ch);
}

function getSeasonid($ckfile,$season,$showid) {
	$fields_string="";
	$url="http://thetvdb.com/?tab=series&id=$showid";
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 


	$result = curl_exec($ch);
	//echo $result;
	$lines = explode("\n",$result);
	$ids=array();
	$matches=array();
	foreach($lines as $line) {
		if (strstr($line,"seasonlink")) {
			$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
			if(preg_match_all("/$regexp/siU", $line, $matches)) { 
				// $matches[2] = array of link addresses 
				// $matches[3] = array of link text - including HTML code 
				//print_r($matches[3]);
			}
		}
	}
	//$found = false;
	$count = 0;
	$seasonid = "";
	foreach($matches[3] as $match) {
		if ($match == $season) {
			//echo "$match == $season\n";
			//$found = true;
			//echo $matches[2][$count];
			$e = explode("seasonid=",$matches[2][$count]);
			$e = explode("&amp;",$e[1]);
			$seasonid=$e[0];
		}
		$count++;
	}
	curl_close($ch);
	return $seasonid;
}

function addSeason($ckfile,$season,$showid) {
	$fields_string="";
	$url="http://thetvdb.com/index.php?tab=series&id=$showid";
	$fields = array(
        	    'Season'=>urlencode($season),
	            'function'=>urlencode("Add Season"),
        	);


		$ch = curl_init();
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
		rtrim($fields_string,'&');

		//set the url, number of POST vars, POST data
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_POST,count($fields));
		curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
		curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
		curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 

		//execute post
		$result = curl_exec($ch);
		curl_close($ch);	

}


function checkIfSeason($ckfile,$season,$showid) {
	$fields_string="";
	$url="http://thetvdb.com/?tab=series&id=$showid";
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 


	//execute post
	$result = curl_exec($ch);
	//echo $result;
	$lines = explode("\n",$result);
	$ids=array();
	$matches=array();
	foreach($lines as $line) {
		if (strstr($line,"seasonlink")) {
			$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
			if(preg_match_all("/$regexp/siU", $line, $matches)) { 
				// $matches[2] = array of link addresses 
				// $matches[3] = array of link text - including HTML code 
				//print_r($matches[3]);
			}
		}
	}
	$found = false;
	foreach($matches[3] as $match) {
		if ($match == $season) {
			$found = true;
		}
	}
	curl_close($ch);
	return $found;
}



function getShowId($ckfile,$show) {
	$fields_string="";

	if ($show == "House Hunters") {
		return 73182;
	}
	$show=urlencode($show);
	$url="http://thetvdb.com/index.php?string=$show&searchseriesid=&tab=listseries&function=Search";
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
	curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
	curl_setopt($ch,CURLOPT_COOKIEFILE, $ckfile); 


	//execute post
	$result = curl_exec($ch);
	//echo $result;
	$lines = explode("\n",$result);
	$ids=array();
	foreach($lines as $line) {
		if (strstr($line,"?tab=series&amp;id")) {
			$e = explode("id=",$line);
			$e = explode("&amp;",$e[1]);
			$id = $e[0];
			array_push($ids,$id);
		}
	}
	curl_close($ch);
	if (sizeof($ids) != 1) {
		return -1;
	}

	return $ids[0];
}


function login($ckfile,$username,$password) {
	$fields_string="";
	$url="http://thetvdb.com/index.php?tab=login";
	$fields = array(
        	    'username'=>urlencode($username),
	            'password'=>urlencode($password),
        	    'function'=>urlencode("Log In"),
	            'submit'=>urlencode("Log In")
        	);


	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
		rtrim($fields_string,'&');
		$ch = curl_init();

		//set the url, number of POST vars, POST data
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_POST,count($fields));
		curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
		curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 

		//execute post
		$result = curl_exec($ch);

		//echo $result;
		$found = 0;
		$lines = explode("\n",$result);
		foreach($lines as $line) {
			if (strstr($line,"logout")) {
				$found = 1;	
				break;
			}
		}

		if ($found != 1) {
			print "Porkins, Didn't Make it...\n";
			exit;
		}
		//echo "Red Leader Checking in...\n";
		//close connection
		curl_close($ch);
}

function startsWith($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

?>
